//
//  RCTNativeToast.m
//  leosmart
//
//  Created by cc on 2025/4/25.
//

#import "RCTNativeToast.h"
#import "UIView+Toast.h"
#import "Utils.h"
@implementation RCTNativeToast
RCT_EXPORT_MODULE()
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {
  return std::make_shared<facebook::react::NativeToastSpecJSI>(params);
}

- (UIWindow *)getKeyWindow {
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            if ([scene isKindOfClass:[UIWindowScene class]] && 
                scene.activationState == UISceneActivationStateForegroundActive) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        return window;
                    }
                }
            }
        }
    }
    // Fallback for iOS 12 and earlier
    UIApplication *app = [UIApplication sharedApplication];
    if (@available(iOS 15.0, *)) {
        return app.keyWindow;
    } else {
        return app.windows.firstObject;
    }
}
- (void)showToast:(JS::NativeToast::Options &)options{
  NSString *message = options.message(); // required
  NSNumber *durationNum = options.duration().has_value() ? @(options.duration().value()) : @(2.0);
  NSString *position =options.position(); // optional
  const NSString *toastPosition= CSToastPositionCenter;
  if([position  isEqualToString:@"TOP"]){
    toastPosition=CSToastPositionTop;
  }else if ([position isEqual:@"BOTTOM"]){
    toastPosition=CSToastPositionBottom;
  }
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *window = [self getKeyWindow];
      [
        window makeToast:message duration:durationNum.doubleValue position:toastPosition
      ];
  });
}
- (void)showCustomToast:(JS::NativeToast:: CustomOptions&)options {
  // ✅ 提前取出并 retain 所有值，避免在 dispatch_async 中访问 C++ 生命周期对象
  NSString *message = options.message(); // required
  NSNumber *durationNum = options.duration().has_value() ? @(options.duration().value()) : @(2.0);
  NSString *position =options.position(); // optional
  std::optional<JS::NativeToast::Icon> icon = options.icon();
  NSDictionary *iconDict = nil;
  NSAttributedString *attributedString=nil;
  if (icon.has_value()) {
    UIFont *font =[UIFont fontWithName:@"iconfont" size:icon.value().size()];
    UIColor *uiColor = [Utils ColorFromHexCode:icon.value().color()];
    attributedString = [[NSAttributedString alloc] initWithString:icon.value().glyph() attributes:@{NSFontAttributeName: font, NSForegroundColorAttributeName: uiColor}];
  }
  // ✅ 决定位置常量
  // ✅ 加载图片（如果有）
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *window = [self getKeyWindow];
    if (window && message.length > 0) {
      UIView *toastView = [self buildToastViewWithMessage:message icon:attributedString];
      [window addSubview:toastView];
      if ([position isEqualToString:@"TOP"]) {
          [NSLayoutConstraint activateConstraints:@[
              [toastView.centerXAnchor constraintEqualToAnchor:window.centerXAnchor],
              [toastView.topAnchor constraintEqualToAnchor:window.safeAreaLayoutGuide.topAnchor constant:40]
          ]];
      } else if ([position isEqualToString:@"BOTTOM"]) {
          [NSLayoutConstraint activateConstraints:@[
              [toastView.centerXAnchor constraintEqualToAnchor:window.centerXAnchor],
              [toastView.bottomAnchor constraintEqualToAnchor:window.safeAreaLayoutGuide.bottomAnchor constant:-40]
          ]];
      } else {
          [NSLayoutConstraint activateConstraints:@[
              [toastView.centerXAnchor constraintEqualToAnchor:window.centerXAnchor],
              [toastView.centerYAnchor constraintEqualToAnchor:window.centerYAnchor]
          ]];
      }
      [
        window showToast:toastView duration:durationNum.doubleValue position:nil completion:nil
      ];
    }
  });
}

- (void)makeToastActivity{
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *window= [self getKeyWindow];
    
    // 创建模态背景视图，禁止用户交互
    UIView *modalBackground = [[UIView alloc] init];
    modalBackground.backgroundColor = [UIColor colorWithWhite:0 alpha:0.0]; // 半透明黑色背景
    modalBackground.tag = 999; // 设置标签用于后续移除
    modalBackground.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 添加到窗口
    [window addSubview:modalBackground];
    
    // 设置约束，覆盖整个窗口
    [NSLayoutConstraint activateConstraints:@[
        [modalBackground.topAnchor constraintEqualToAnchor:window.topAnchor],
        [modalBackground.bottomAnchor constraintEqualToAnchor:window.bottomAnchor],
        [modalBackground.leadingAnchor constraintEqualToAnchor:window.leadingAnchor],
        [modalBackground.trailingAnchor constraintEqualToAnchor:window.trailingAnchor]
    ]];
    
    // 显示 Toast 活动指示器
    [window makeToastActivity:CSToastPositionCenter];
  });
}
-(void)hideToastActivity{
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *window= [self getKeyWindow];
    
    // 隐藏 Toast 活动指示器
    [window hideToastActivity];
    
    // 移除模态背景视图
    UIView *modalBackground = [window viewWithTag:999];
    if (modalBackground) {
      [modalBackground removeFromSuperview];
    }
  });
}
- (UIView *)buildToastViewWithMessage:(NSString *)message icon:(NSAttributedString *)icon {
    // 容器视图
    UIView *toastView = [[UIView alloc] init];
    toastView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    toastView.layer.cornerRadius = 8;
    toastView.clipsToBounds = YES;
    toastView.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 垂直堆栈视图（Flex 式布局）
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.alignment = UIStackViewAlignmentCenter;  // 水平居中
    stackView.distribution = UIStackViewDistributionEqualSpacing;  // 修改为等间距分布
    stackView.spacing = 30;  // 设置间距为30
    stackView.translatesAutoresizingMaskIntoConstraints = NO;
    [toastView addSubview:stackView];
    
    [NSLayoutConstraint activateConstraints:@[
        [stackView.topAnchor constraintEqualToAnchor:toastView.topAnchor constant:24],
        [stackView.bottomAnchor constraintEqualToAnchor:toastView.bottomAnchor constant:-24],
        [stackView.leadingAnchor constraintEqualToAnchor:toastView.leadingAnchor constant:16],
        [stackView.trailingAnchor constraintEqualToAnchor:toastView.trailingAnchor constant:-16],
    ]];
    
    // 如果有图标，添加图标
  if (icon) {
      UILabel *label = [[UILabel alloc] init];
      label.attributedText = icon;
      label.translatesAutoresizingMaskIntoConstraints = NO;
      
      [stackView addArrangedSubview:label];
  }

    
    // 添加文本标签
    UILabel *messageLabel = [[UILabel alloc] init];
    messageLabel.text = message;
    messageLabel.font = [UIFont systemFontOfSize:14];
    messageLabel.textColor = [UIColor whiteColor];
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [stackView addArrangedSubview:messageLabel];
    
    // 固定宽度 + 最小高度（类似 flex 布局）
    [NSLayoutConstraint activateConstraints:@[
        [toastView.widthAnchor constraintEqualToConstant:120],  // 固定宽度
        [toastView.heightAnchor constraintGreaterThanOrEqualToConstant:100],  // 最小高度
        // 确保文字宽度不超过 Toast 内容区域
        [messageLabel.widthAnchor constraintEqualToAnchor:stackView.widthAnchor]
    ]];
    
    // 强制立即布局计算
    [toastView layoutIfNeeded];
    
    return toastView;
}
 
@end

 
